
var apiHost = wx.getStorageSync('apiHost');
var apiUpLoad = wx.getStorageSync('apiUpLoad');        //上传外网图片地址

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var openId = wx.getStorageSync('openId');     //用户openId获取
    var phone = wx.getStorageSync('phone');       //用户phone获取
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取
    var userId = wx.getStorageSync('userId'); //用户userInfo获取

    that.setData({
      openId: openId,
      apiUpLoad: apiUpLoad
    })
    /**
    * 判断是否有手机号
    */
    if (phone == '') {
      that.setData({
        phone: ''
      })
    } else {
      that.setData({
        phone: phone
      })
    }

    if (userInfo != '') {
      that.setData({
        userInfo: userInfo
      });
    }

    // 判断openid弹窗授权
    if (openId != '') {
      that.setData({
        openId: openId,
        userId: userId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }
  },

  /**
   * 发布普通小程序
   */
  publishOrdinaryCollage :function(){
    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    wx.reLaunch({
      url: '../ordinaryCollage/firstOrdinaryCollage/firstOrdinaryCollage',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },
  
  /**
   * 客服电话
   */
  kefu : function(){
    wx.makePhoneCall({
      phoneNumber: '1340000' //仅为示例，并非真实的电话号码
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 阶梯 拼团
   */
  ladderCollage:function(){
    wx.showModal({
      title: '提示',
      content: '功能完善中...',
      showCancel:false,
      success: function (res) {

      }
    })
  },
  /**
   * 分销拼团
   */
  distributionCollage:function(){
    wx.showModal({
      title: '提示',
      content: '功能完善中...',
      showCancel: false,
      success: function (res) {

      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openId = wx.getStorageSync('openId');     //用户openId获取
    var userId = wx.getStorageSync('userId');     //用户userId获取

    if (openId != '') {
      that.setData({
        openId: openId,
        userId: userId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },
  /**
  * 手机号授权方式
  */
  getPhoneNumberF: function (res) {
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail;
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    } else {
      wx.showToast({
        title: '授权后即可购买',
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },

  /**
  * 解密用户登录完成后的url (用户手机号)
  */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'hpp/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;

          that.reginPhoneOpenid(phone);
        } else {
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },
  //表单提交
  reginPhoneOpenid: function (userPhone) {
    var that = this;
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取
    var nickName = userInfo.nickName;     //	昵称
    var avatarUrl = userInfo.avatarUrl;   //用户头像
    var openId = that.data.openId;   //openID
    console.log(openId)
    console.log(nickName)
    console.log(avatarUrl)
    console.log(userPhone)

    wx.request({
      url: apiHost + "hpp/user/auth",
      data: {
        openId: openId,
        phone: userPhone,
        nickName: nickName,
        avatarUrl: avatarUrl
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == '10000') {
          that.setData({
            phone: userPhone
          })
          wx.setStorageSync('phone', userPhone);
          var userId = res.data.data.id
          wx.setStorageSync('userId', userId); 
          that.publishOrdinaryCollage();//跳转发布
        } else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail :function(){
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    });
  },

  //按钮获取用户信息
  bindGetUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'hpp/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果

        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          that.getuserId(userInfo_.openId);       //获取userId
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  /**
   * 获取userId
   */
  getuserId: function (openId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: "loading",
      mask: true
    });

    wx.request({
      url: apiHost + 'hpp/user/userInfoByOpenId',
      method: 'GET',
      header: {
        "content-type": 'application/json'
      },
      data: {
        openId: openId
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        var userIdFlag = that.data.userId;

        wx.hideLoading();   //隐藏加载loading
        if ("10000" == code) {
          var userId = res.data.data.id;

          that.setData({
            userId: userId
          });

          wx.setStorageSync("userId", userId)
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 5000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 5000,
          mask: true
        });
      }
    })
  },
})